package com.hancai.barrage.service.impl;

import com.hancai.barrage.mapper.DepartmentMapper;
import com.hancai.barrage.model.Page;
import com.hancai.barrage.model.TreeData;
import com.hancai.barrage.pagehelper.QueryObject;
import com.hancai.barrage.pojo.Department;
import com.hancai.barrage.service.SysDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 涵菜
 * @version 1.0
 */
@Service
public class DepartmentServiceImpl implements SysDepartmentService {
    private final DepartmentMapper departmentMapper;

    public DepartmentServiceImpl(DepartmentMapper departmentMapper) {
        this.departmentMapper = departmentMapper;
    }

    @Override
    public void save(Department obj) {
        departmentMapper.insert(obj);
    }

    @Override
    public void updateById(Department obj) {
        departmentMapper.updateByPrimaryKey(obj);
    }

    @Override
    public void deleteById(Long id) {
        departmentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Department selectById(Long id) {
        return departmentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Department> selectAll() {
        return departmentMapper.selectAll();
    }
    @Override
    public Page<Department> query(QueryObject qo) {
        Long total=departmentMapper.selectForCount(qo);
        if(total==0){
            return Page.empty(qo.getPageNum(),qo.getPageSize());
        }
        List<Department>list=departmentMapper.selectForList(qo);
        return new Page<>(qo.getPageNum(), qo.getPageSize(),total,list);
    }


    /**
     * @return 返回部门树的集合
     */
    @Override
    public List<TreeData>queryTreeList(){
        List<TreeData>treeList=new ArrayList<>();
        //方法内部是没有多线程的
        Map<Long,TreeData> cache=new HashMap<>();
        //1，先查询出所有的部门对象
        List<Department> departments = departmentMapper.selectAll();
        //2，将所有部门转换为treeData对象，并将其存入 map(K=id,V=TreeData对象)
        TreeData treeData=null;
        for (Department department : departments) {
            treeData=new TreeData(department.getId(),department.getName());
            //判断是否为根元素（总部）
            if(department.getParent()==null){
                //将根元素存入数集合
                treeList.add(treeData);
            }
            //将当前转换后的数据存入map
            cache.put(treeData.getId(),treeData);
        }
        //3，遍历整个部门集合  hashMap的K-Set(KeySet类) V-Collection(Values类)
        for(Department child:departments){
            //3.1，获取到当前部门，用当前部门的id，从map中查找父元素
            Department parent = child.getParent();
            if(parent!=null){
                TreeData parentData = cache.get(parent.getId());
                //3.2，如果父元素存在，就将自己加入到父元素的children中去
                parentData.getChildren().add(cache.get(child.getId()));
            }
        }
        return treeList;
    }

}
